package kgc.crm.aop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import kgc.crm.model.User;
import kgc.crm.util.CommonResult;
import kgc.crm.util.Constant;
import kgc.crm.util.JWTManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
@Aspect //作⽤是把当前类标识为⼀个切⾯供容器读取
public class TokenVerifAop {
    public static void main(String[] args) {
        String a ="a";
        String b ="a";
        String c = a;
        User user = new User();
        User user1 = new User();
        System.out.println(user);
        System.out.println(user1);
        System.out.println(user == user1);
        System.out.println(user.equals(user1));

        System.out.println(a.equals(b));
        System.out.println(a == b);
        System.out.println(a.equals(c));
        System.out.println(a == c);

    }
    //切点
    @Pointcut("@annotation(kgc.crm.annotation.VerificationToken)")
    public void tokenVerif(){
    }
//JoinPoint切入点
    @Around("tokenVerif()")  //环绕增强
    public Object verrifcation(ProceedingJoinPoint   joinPoint){
        //验证token 的完整性
        //在aop容器中获取request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.
                resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //获取请求头 api_token
        String apitoken = request.getHeader(Constant.API_TOKEN);
        if (StringUtils.isBlank(apitoken)){
            log.error("TOKEN验证不通过,API_TOKEN不能为空");
            return new ResponseEntity<CommonResult<String>>(new CommonResult<>(500,"ERROR","验证不通过"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        //通过jwt获取token   调用UserByToken方法验证token是否过期
        User token = JWTManager.getUserByToken(apitoken);
//        User token = JWTManager.getUserByToken(apitoken);
        if (token == null){
            log.error("TOKEN验证不通过");
            return new ResponseEntity<CommonResult<String>>(new CommonResult<>(500,"ERROR","验证不通过"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        Object proceed = null;
        try {
            //如果通过验证，则直接调用请求方法
            proceed = joinPoint.proceed();
        }catch (Throwable throwable){
            throwable.printStackTrace();
        }
        return proceed;
    }
}
